import { useEffect, useState } from 'react';
import { ethers } from 'ethers';
import { Method } from '../types/types';
import { parseAbi } from '../utils/abiParser';
import { useAppContext } from '../contexts/AppContext';
import { useEthersContext } from '../contexts/EthersContext';

export const useContract = () => {
    const { state, dispatch } = useAppContext();
    const { provider } = useEthersContext();
    const [contract, setContract] = useState<ethers.Contract | null>(null);

    useEffect(() => {
        if (state.abi && provider && state.contractAddress) {
            try {
                const parsedAbi = parseAbi(state.abi);
                dispatch({ type: 'SET_METHODS', payload: parsedAbi });

                const newContract = new ethers.Contract(
                    state.contractAddress,
                    state.abi,
                    provider
                );
                setContract(newContract);
            } catch (error) {
                dispatch({ type: 'SET_ERROR', payload: error instanceof Error ? error.message : String(error) });
            }
        } else {
            setContract(null);
        }
    }, [state.abi, provider, state.contractAddress, dispatch]);

    const callMethod = async (method: Method, args: any[], isReadOnly: boolean) => {
        if (!contract) {
            dispatch({ type: 'SET_ERROR', payload: 'Contract not initialized' });
            return;
        }

        try {
            let result;
            if (isReadOnly) {
                result = await contract[method.name](...args);
            } else {
                // For write methods, we'd need a signer
                dispatch({ type: 'SET_ERROR', payload: 'Write methods not supported in this demo' });
                return;
            }

            dispatch({ type: 'SET_RESULT', payload: result });
        } catch (error) {
            dispatch({ type: 'SET_ERROR', payload: error instanceof Error ? error.message : String(error) });
        }
    };

    return { contract, callMethod };
};